<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <button @click="$router.back()" class="mr-4 p-2 text-gray-500 hover:text-gray-700 focus:outline-none">
          <ArrowLeftIcon class="h-6 w-6" />
        </button>
        <h2 class="text-2xl font-semibold text-gray-800">
          {{ isEdit ? '编辑申请' : '新建申请' }}
        </h2>
      </div>
    </div>

    <div class="max-w-4xl mx-auto">
      <div class="bg-white rounded-xl shadow-lg p-6">
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- 基本信息 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label for="category" class="block text-sm font-medium text-gray-700">设备类别 *</label>
                <select
                  id="category"
                  v-model="form.category"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                >
                  <option value="">请选择设备类别</option>
                  <option value="计算机设备">计算机设备</option>
                  <option value="实验仪器">实验仪器</option>
                  <option value="化学仪器">化学仪器</option>
                  <option value="生物仪器">生物仪器</option>
                  <option value="其他设备">其他设备</option>
                </select>
                <p v-if="errors.category" class="mt-1 text-sm text-red-600">{{ errors.category }}</p>
              </div>

              <div>
                <label for="name" class="block text-sm font-medium text-gray-700">设备名称 *</label>
                <input
                  type="text"
                  id="name"
                  v-model="form.name"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入设备名称"
                />
                <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
              </div>
            </div>
          </div>

          <!-- 规格要求 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">规格要求</h3>
            <div>
              <label for="specification" class="block text-sm font-medium text-gray-700">规格要求 *</label>
              <textarea
                id="specification"
                v-model="form.specification"
                required
                rows="4"
                class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                placeholder="请详细描述设备规格要求"
              ></textarea>
              <p v-if="errors.specification" class="mt-1 text-sm text-red-600">{{ errors.specification }}</p>
            </div>
          </div>

          <!-- 数量和价格 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">数量和价格</h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div>
                <label for="quantity" class="block text-sm font-medium text-gray-700">申请数量 *</label>
                <input
                  type="number"
                  id="quantity"
                  v-model.number="form.quantity"
                  required
                  min="1"
                  max="100"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入申请数量"
                />
                <p v-if="errors.quantity" class="mt-1 text-sm text-red-600">{{ errors.quantity }}</p>
              </div>

              <div>
                <label for="unitPrice" class="block text-sm font-medium text-gray-700">预估单价 (元) *</label>
                <input
                  type="number"
                  id="unitPrice"
                  v-model.number="form.unitPrice"
                  required
                  min="0"
                  step="0.01"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入预估单价"
                />
                <p v-if="errors.unitPrice" class="mt-1 text-sm text-red-600">{{ errors.unitPrice }}</p>
              </div>

              <div>
                <label for="urgency" class="block text-sm font-medium text-gray-700">紧急程度 *</label>
                <select
                  id="urgency"
                  v-model="form.urgency"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                >
                  <option value="">请选择紧急程度</option>
                  <option value="LOW">低</option>
                  <option value="MEDIUM">中</option>
                  <option value="HIGH">高</option>
                </select>
                <p v-if="errors.urgency" class="mt-1 text-sm text-red-600">{{ errors.urgency }}</p>
              </div>
            </div>
          </div>

          <!-- 申请原因 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">申请原因</h3>
            <div>
              <label for="reason" class="block text-sm font-medium text-gray-700">申请原因 *</label>
              <textarea
                id="reason"
                v-model="form.reason"
                required
                rows="5"
                class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                placeholder="请详细说明申请原因和用途"
              ></textarea>
              <p v-if="errors.reason" class="mt-1 text-sm text-red-600">{{ errors.reason }}</p>
            </div>
          </div>

          <!-- 预估总价显示 -->
          <div v-if="form.quantity && form.unitPrice" class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div class="flex items-center">
              <CalculatorIcon class="h-5 w-5 text-blue-500 mr-2" />
              <span class="text-sm font-medium text-blue-800">预估总价：</span>
              <span class="text-lg font-bold text-blue-900 ml-2">¥{{ (form.quantity * form.unitPrice).toLocaleString() }}</span>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-3 pt-6 border-t border-gray-200">
            <button
              type="button"
              @click="$router.back()"
              class="px-6 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              取消
            </button>
            <button
              type="submit"
              :disabled="loading"
              class="px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ loading ? '提交中...' : '提交申请' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeftIcon, CalculatorIcon } from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const isEdit = computed(() => !!route.params.id)

const form = reactive({
  category: '',
  name: '',
  specification: '',
  quantity: 1,
  unitPrice: 0,
  urgency: 'MEDIUM',
  reason: ''
})

const errors = reactive({})

// 验证表单
const validateForm = () => {
  // 清空之前的错误
  Object.keys(errors).forEach(key => delete errors[key])
  
  let isValid = true

  if (!form.category) {
    errors.category = '请选择设备类别'
    isValid = false
  }

  if (!form.name.trim()) {
    errors.name = '请输入设备名称'
    isValid = false
  }

  if (!form.specification.trim()) {
    errors.specification = '请输入规格要求'
    isValid = false
  }

  if (!form.quantity || form.quantity <= 0) {
    errors.quantity = '请输入有效的申请数量'
    isValid = false
  }

  if (!form.unitPrice || form.unitPrice < 0) {
    errors.unitPrice = '请输入有效的预估单价'
    isValid = false
  }

  if (!form.urgency) {
    errors.urgency = '请选择紧急程度'
    isValid = false
  }

  if (!form.reason.trim()) {
    errors.reason = '请输入申请原因'
    isValid = false
  }

  return isValid
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  try {
    loading.value = true
    
    // 构建请求数据，字段名需要匹配后端DTO
    const requestData = {
      applicationDate: new Date().toISOString().split('T')[0], // 当前日期
      equipmentName: form.name,
      equipmentCategory: form.category,
      quantity: form.quantity,
      unitPrice: form.unitPrice,
      reason: form.reason
    }
    
    if (isEdit.value) {
      // 更新申请
      await request.put(`/equipment-application/${route.params.id}`, requestData)
      showMessage('申请更新成功', 'success')
    } else {
      // 新建申请
      await request.post('/equipment-application', requestData)
      showMessage('申请提交成功', 'success')
    }
    
    router.push('/equipment-application')
    
  } catch (error) {
    console.error('提交申请失败:', error)
    showMessage('提交申请失败', 'error')
  } finally {
    loading.value = false
  }
}

// 加载申请数据（编辑时）
const loadApplication = async () => {
  if (!isEdit.value) return

  try {
    loading.value = true
    const applicationId = route.params.id
    
    // 调用真实API加载申请数据
    const response = await request.get(`/equipment-application/${applicationId}`)
    const application = response.data
    
    // 映射API数据到表单字段
    form.category = application.category || ''
    form.name = application.equipmentName || ''
    form.specification = application.specification || ''
    form.quantity = application.quantity || 1
    form.unitPrice = application.unitPrice || 0
    form.urgency = application.urgency || 'MEDIUM'
    form.reason = application.purpose || ''
    
  } catch (error) {
    console.error('加载申请数据失败:', error)
    showMessage('加载申请数据失败', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadApplication()
})
</script>